<template>
  <!-- 添加或修改盘点计划对话框 -->
  <el-dialog :title="title" v-model="open" v-if="open" width="1200px" append-to-body>
    <div class="tags">
      <div v-for="(tag, index) in tags" :key="index" :class="['tag', { active: index + 1 === active }]">
        <div class="tag-num">{{ index + 1 }}</div>
        <div class="tag-name">{{ tag.name }}</div>
      </div>
    </div>
    <div v-show="active === 1">
      <el-form ref="goodsForm" :model="form" class="goods_add" :rules="rules" label-width="90px"
        style="padding-left: 10%">
        <el-form-item label="商品条码:" prop="goodsSku">
          <el-input ref="firstInput" v-model="form.goodsSku" placeholder="请输入条码"></el-input>
        </el-form-item>
        <el-form-item label="商品名称:" prop="goodsName">
          <el-input v-model="form.goodsName"></el-input>
        </el-form-item>
        <el-form-item label="货号:" prop="itemNo">
          <div style="display: flex" :style="'width: 490px'" v-if="!form.id">
            <el-input v-model="form.itemNo" :disabled="itemNoDisabled || !!form.id"></el-input>
            <el-checkbox style="margin-left: 10px" label="1" @change="isAdd">自动递增</el-checkbox>
          </div>

          <el-input v-else v-model="form.itemNo" :disabled="itemNoDisabled || !!form.id"></el-input>
        </el-form-item>
        <el-form-item label="商品分类:" prop="classifyId">
          <el-tree-select v-model="form.classifyId" :data="categoryList"
            :props="{ value: 'id', label: 'classifyName', children: 'children' }" value-key="id" placeholder="选择产品分类"
            check-strictly />
        </el-form-item>
        <el-form-item label="商品品牌:" prop="brandId">
          <el-select style="width: 400px;" v-model="form.brandId" placeholder="请选择">
            <el-option v-for="item in brandList" :key="item.id" :label="item.brandName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片:" prop="remark" class="goods_imgs">
          <el-upload class="avatar-uploader el-upload" :headers="headers"
            :on-success="(res, file) => handleUploadSuccess(res, file, 'packImg')" :show-file-list="false"
            :action="uploadUrl">
            <img v-if="form.packImg" :src="form.packImg" class="avatar">
            <div v-else class="upload-text">点击上传主图</div>
            <div class="btn" v-if="form.packImg">
              <el-button type="text" icon="el-icon-delete" @click.prevent="deleteImg('packImg')"></el-button>
            </div>
          </el-upload>
          <el-upload class="avatar-uploader el-upload" :headers="headers"
            :on-success="(res, file) => handleUploadSuccess(res, file, 'auxiliaryImg')" :show-file-list="false"
            :action="uploadUrl">
            <img v-if="form.auxiliaryImg" :src="form.auxiliaryImg" class="avatar">
            <div v-else class="upload-text">点击上传包装图</div>
            <div class="btn" v-if="form.auxiliaryImg">
              <el-button type="text" icon="el-icon-delete" @click.prevent="deleteImg('auxiliaryImg')"></el-button>
            </div>
          </el-upload>
          <el-upload class="avatar-uploader el-upload" :headers="headers"
            :on-success="(res, file) => handleUploadSuccess(res, file, 'primarilyImg')" :show-file-list="false"
            :action="uploadUrl">
            <img v-if="form.primarilyImg" :src="form.primarilyImg" class="avatar">
            <div v-else class="upload-text">点击上传图片</div>
            <div class="btn" v-if="form.primarilyImg">
              <el-button type="text" icon="el-icon-delete" @click.prevent="deleteImg('primarilyImg')"></el-button>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="支持代发:" prop="planName">
          <el-select style="width: 400px;" v-model="form.behalfStatus" placeholder="请选择">
            <el-option v-for="item in drop_shipping" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品规格:" prop="goodsSize">
          <el-input v-model="form.goodsSize"></el-input>
        </el-form-item>
        <el-form-item label="默认供应商:" prop="supplierId">
          <el-select style="width: 400px;" v-model="form.supplierId" placeholder="请选择">
            <el-option v-for="item in supplierList" :key="item.id" :label="item.supplierName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-card class="box-card" shadow="never" style="margin-left:90px">
          <div slot="header" class="clearfix">
            <span>商品单位</span>
          </div>
          <el-table v-loading="dialogLoading" :data="dataSource">
            <el-table-column label="单位类型" align="center">
              <template #default="{ scope }">
                基本单位
              </template>
            </el-table-column>
            <el-table-column label="单位名称" align="center">
              <template #default="{ scope }">
                <el-form-item prop="goodsUnit" class="unit-list">
                  <el-input v-model="form.goodsUnit"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="单位换算" align="center">
              <template #default="{ scope }">
                1
              </template>
            </el-table-column>
            <el-table-column label="单位条码" align="center">
              <template #default="{ scope }">
                <el-form-item prop="barCode" class="unit-list">
                  <el-input v-model="form.barCode"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="允许销售" align="center">
              <template #default="{ scope }">
                <el-checkbox v-model="form.accept">{{ form.saleStatus ? '允许' : '不允许' }}</el-checkbox>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form>
    </div>
    <el-card class="box-card" shadow="never" v-show="active === 2">
      <div slot="header" class="clearfix">
        <span>商品价格</span>
        <el-button style="float: right; margin-right: 10px" type="danger" icon="el-icon-s-operation"
          @click="handleCustom">自定义价格</el-button>
      </div>
      <el-table v-loading="dialogLoading" :data="priceData">
        <el-table-column label="单位名称" align="center" width="150">
          <template #default>
            {{ form.goodsUnit }}
          </template>
        </el-table-column>
        <el-table-column v-for="(col, index) in columns" :key="index" :label="col.title" align="center"
          :prop="col.dataIndex" :width="col.width">
          <template #default="{ scope }">
            <el-input v-model="scope.row[col.dataIndex]"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="box-card" shadow="always" v-show="active === 3">
      <div slot="header" class="clearfix">
        <span>商品详情</span>
      </div>
      <!-- <editor v-model="form.goodsDetails" :init="init" :disabled="disabled" style="min-height: 200px">
      </editor> -->
    </el-card>
    <customPriceForm ref="customPriceForm" @ok="customOk" />

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="up()" v-if="active > 1">上一步</el-button>
        <el-button type="primary" @click="next()" v-if="active < 3">下一步</el-button>
        <el-button type="primary" @click="submitForm" v-if="active === 3">提交</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, defineExpose } from 'vue';

// import 'tinymce/themes/silver'  //编辑器主题，不引入则报错
// import 'tinymce/icons/default'  //引入编辑器图标icon，不引入则不显示对应图标,引入报错
//可能是node_modules\tinymce目录下缺失icons文件夹及其内容的js文件

// 引入编辑器插件（基本免费插件都在这儿了）
// import 'tinymce/plugins/advlist'  //高级列表
// import 'tinymce/plugins/anchor'  //锚点
// import 'tinymce/plugins/autolink'  //自动链接
// import 'tinymce/plugins/autoresize'  //编辑器高度自适应,注：plugins里引入此插件时，Init里设置的height将失效
// import 'tinymce/plugins/autosave'  //自动存稿
// import 'tinymce/plugins/charmap'  //特殊字符
// import 'tinymce/plugins/code'  //编辑源码
// import 'tinymce/plugins/codesample'  //代码示例
// import 'tinymce/plugins/directionality'  //文字方向
// import 'tinymce/plugins/emoticons'  //表情
// import 'tinymce/plugins/fullscreen'  //全屏
// import 'tinymce/plugins/help'  //帮助
// import 'tinymce/plugins/image'  //插入编辑图片
// import 'tinymce/plugins/importcss'  //引入css
// import 'tinymce/plugins/insertdatetime'  //插入日期时间
// import 'tinymce/plugins/link'  //超链接
// import 'tinymce/plugins/lists' //列表插件
// import 'tinymce/plugins/media' //插入编辑媒体
// import 'tinymce/plugins/nonbreaking' //插入不间断空格
// import 'tinymce/plugins/pagebreak' //插入分页符
// import 'tinymce/plugins/preview'//预览
// import 'tinymce/plugins/quickbars'  //快速工具栏
// import 'tinymce/plugins/save'  //保存
// import 'tinymce/plugins/searchreplace'  //查找替换
// // import 'tinymce/plugins/spellchecker'  //拼写检查，暂未加入汉化，不建议使用
// import 'tinymce/plugins/table'  //表格
// import 'tinymce/plugins/toc'  //目录生成器
// import 'tinymce/plugins/visualblocks'  //显示元素范围
// import 'tinymce/plugins/visualchars'  //显示不可见字符
// import 'tinymce/plugins/wordcount'  //字数统计
//附件下载
import modelMixin from "@/mixins/modelMixin";
import request from '@/utils/request';
import { getBrandAllList } from '@/api/goods/brand/index';
import { getSupplierAllList } from '@/api/goods/supplier/index';
import { getToken } from "@/utils/auth";
// import customPriceForm from './customPriceForm.vue';
import { refreshCache } from '@/api/goods/order';
import goods from '@/api/goods/goods';
const plugins = 'attachment print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern autosave '
const toolbar = 'attachment fullscreen undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | \
styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
table image media charmap hr pagebreak insertdatetime print preview | code selectall searchreplace visualblocks | indent2em lineheight formatpainter axupimgs'
const open = ref(false);
const initData = () => ({
  goodsSku: "",
  goodsName: "",
  itemNo: "",
  classifyId: "",
  brandId: "",
  packImg: "",
  auxiliaryImg: "",
  primarilyImg: "",
  behalfStatus: "",
  goodsSize: "",
  supplierId: "",
  goodsUnit: "",
  barCode: "",
  accept: false,
  goodsDetails: "",
  costPrice: "",
  purchasePrice: "",
  wholesalePrice: "",
  salePrice: "",
  upsetPrice: "",
  retailPrice: "",
  customPrice80: "",
  goodsRedisList: [],

});
const active = ref(1);
const form = reactive(initData());
const rules = ref({
  goodsName: [
    { required: true, message: "请输入商品名称", trigger: "change" },
  ],
  itemNo: [
    { required: true, message: "请输入商品货号", trigger: "change" },
  ],
  classifyId: [
    { required: true, message: "请选择商品分类", trigger: "change" },
  ],
  goodsUnit: [
    { required: true, message: "请输入基本单位名称", trigger: "change" },
  ],
  barCode: [
    { required: true, message: "请输入单位条码", trigger: "change" },
  ],
});

const { proxy } = getCurrentInstance();
const { drop_shipping } = toRefs<any>(proxy?.useDict('drop_shipping'));
const firstInput = ref(null);
const inputWidth = ref(null);
const warehouseList = ref([]);
const dialogLoading = ref(false);
const dataSource = ref([{}]);
const priceData = ref([{}]);
const categoryList = ref([]);
const brandList = ref([]);
const supplierList = ref([]);
const dropShipping = ref([]);
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_API + '/profile/upload');
const itemNoDisabled = ref(false);
const loading = ref(false);


const fileList = ref([import.meta.env.VITE_APP_BASE_API + '/profile/upload/2024/06/06/p (4)_20240606153034A001.jpg']);
const headers = ref({
  Authorization: "Bearer " + getToken()
});
const tags = ref([
  { name: "商品基础信息", complete: false },
  { name: "商品价格", complete: false },
  { name: "商品详情描述", complete: false },
]);
const columns = ref([]);
const disabled = ref(false);
const urls = ref({
  list: "/order/goodsCategory/allList",
});
const detailUrls = ref({
  doudian: "/doudian/doudianGoodsDetail/",
});
const columns1 = ref([
  { title: '单位类型', dataIndex: 'type', align: "center" },
  { title: '单位名称', dataIndex: 'name', align: "center" },
  { title: '单位换算', dataIndex: 'g', align: "center" },
  { title: '单位条码', dataIndex: 'barCode', align: "center" },
  { title: '允许销售', dataIndex: 'isSale', align: "center" },
]);
const init = ref({
  language_url: "/tinymce/langs/zh_CN.js",
  language: "zh_CN",
  skin_url: "/tinymce/skins/lightgray",
  height: 300,
  plugins: plugins,
  toolbar: toolbar,
  branding: false,
  menubar: false,
  toolbar_drawer: false,
  convert_urls: false,
  images_upload_handler: (blobInfo, success) => {
    let formData = new FormData();
    formData.append("file", blobInfo.blob(), blobInfo.filename());
    formData.append("biz", "jeditor");
    formData.append("jeditor", "1");
    // uploadAction(
    //   window._CONFIG["domianURL"] + "/sys/common/upload",
    //   formData
    // ).then((res) => {
    //   if (res.success) {
    //     if (res.message == "local") {
    //       const img = "data:image/jpeg;base64," + blobInfo.base64();
    //       success(img);
    //     } else {
    //       let img = getFileAccessHttpUrl(res.message);
    //       success(img);
    //     }
    //   }
    // });
  },
});
const resetData = () => {
  Object.assign(form, initData());
};
const add = () => {
  open.value = true;
  proxy?.$nextTick(() => {
    inputWidth.value = firstInput.value.$el.offsetWidth;
  });
  rules.value.itemNo = [{ required: true, message: "请输入商品货号", trigger: "change" }];
  itemNoDisabled.value = false;
  resetData()
  dataSource.value = [{}];
  priceData.value = [{}];
  active.value = 1;
  // initColumns();
  // getShipping();
  getCategoryAllList();
  getBrandList();
  getSupplierList();
}
const edit = (row) => {
  open.value = true;
  form.value = toRef(row);
  priceData.value = [{}];
  active.value = 1;
  form.value.accept = form.saleStatus == 1;
  rules.value.itemNo = [{ required: true, message: "请输入商品货号", trigger: "change" }];
  itemNoDisabled.value = false;
  dataSource.value = [{}];
  active.value = 1;
  // initColumns();
  // getShipping();
  getCategoryAllList();
  getBrandList();
  getSupplierList();
  if (row.goodsType === '1') {
    getDetail(detailUrls.doudian, row.id);
  }
}
const addRow = () => {
  dataSource.push({});
}
const cancel = () => {
  open.value = false;
}
const itemDelete = (row, index) => {
  dataSource.splice(index, 1);
}
const getListMatByCode = (event, index) => {
  const matCode = event.target.value;
  // Perform logic to get mat by code
}
const getSpaceByWarehouseCode = () => {
  // Perform logic to get space by warehouse code
}
const remoteMethod = (query, row, index) => {
  // Perform remote method logic here
}
const locationChange = (event, row, index) => {
  // Handle location change logic here
}
const uploadRequest = () => {
  // Perform upload request logic here
}
const getDetail = async (url, id) => {
  try {
    const res = await request({
      url: url + id,
      method: 'get'
    });
    if (res.code == 200) {
      form.value = res.data;
    } else {
      proxy?.$modal.msgError(res.msg);
    }
  } catch (error) {
    console.error(error);
  }
}
const next = () => {
  if (active.value === 1) {
    proxy?.$refs.form.validate().then(bol => {
      if (!bol) {
        throw new Error('商品信息填写不完整，请检查！');
      }
    });
  }
  console.log('tags :>> ', tags);
  tags.value[active.value].complete = true;
  if (active.value < 3) {
    active.value++;
  }
}
const up = () => {
  active.value--;
}
const initColumns = async () => {
  try {
    const res = await getDicts("mx_material_price");
    let obj = {};
    columns.value = (res.data || []).map((item) => {
      if (form.id) {
        obj[item.dictValue] = getPrice(form, item);
      }
      return {
        title: item.dictLabel,
        dataIndex: item.dictValue,
        width: Math.max(item.dictLabel.length * 30, 150),
        align: "center",
        sortable: true,
      };
    });
    priceData.value = [obj];
    console.log('priceData :>> ', priceData);
  } catch (error) {
    console.error(error);
  }
}
const getShipping = async () => {
  try {
    const res = await getDicts("mx_drop_shipping");
    dropShipping.value = res.data;
  } catch (error) {
    console.error(error);
  }
}
const getCategoryAllList = async () => {
  var params = {
    url: urls.value.list,
    method: 'get',
  };
  try {
    const res = await request(params);
    var arr = res.filter(item => item.classStatus == 1)
    categoryList.value = proxy?.handleTree(arr, 'id');
  } catch (error) {
    console.error(error);
  }
}
const normalizer = (node) => {
  return {
    id: node.id,
    label: node.classifyName,
    children: node.children
  };
}
const getBrandList = async () => {
  try {
    const res: any = await getBrandAllList();
    brandList.value = res.data;
  } catch (error) {
    console.error(error);
  }
}
const getSupplierList = async () => {
  try {
    const res: any = await getSupplierAllList({ type: 0 });
    supplierList.value = res.data;
  } catch (error) {
    console.error(error);
  }
}
const handleUploadSuccess = (res, file, key) => {
  // 如果上传成功
  if (res.code == 200) {
    form[key] = import.meta.env.VITE_APP_BASE_API + res.fileName;
  } else {
    console.log(res);
  }
}
const deleteImg = (key) => {
  form[key] = '';
}
const handleCustom = () => {
  proxy?.$refs.customPriceForm.show();
}
const customOk = () => {
  // 刷新redis缓存
  refreshCache().then(res => {
    if (res.code == 200) {
      proxy?.$modal.msgSuccess('刷新缓存成功');
      // 重新获取column
      initColumns();
    } else {
      proxy?.$modal.msgError(res.msg);
    }
  }).catch(err => {
    proxy?.$modal.msgError('刷新缓存失败');
  });
}
const isAdd = (val) => {
  if (val) {
    form.itemNo = '';
    itemNoDisabled.value = true;
    rules.itemNo = [{ required: false, message: "请输入商品货号", trigger: "change" }];
  } else {
    itemNoDisabled.value = false;
    rules.itemNo = [{ required: true, message: "请输入商品货号", trigger: "change" }];
  }
  proxy?.$refs.form.validate();
}
const classifyForm = () => {
  let params = { ...form };
  let goodsRedisList = [];
  let defaultPriceArr = [
    "unitName",
    "costPrice",
    "purchasePrice",
    "wholesalePrice",
    "salePrice",
    "upsetPrice",
    "retailPrice",
  ];
  for (let key in priceData[0]) {
    if (defaultPriceArr.includes(key)) {
      params[key] = priceData[0][key];
    } else {
      goodsRedisList.push({
        priceName: key,
        price: priceData[0][key]
      });
    }
  }
  params.goodsRedisList = goodsRedisList;
  params.saleStatus = params.accept ? 1 : 0;
  form.value = params;
  return params;
}
const getPrice = (row, child) => {
  let defaultPriceArr = [
    "unitName",
    "costPrice",
    "purchasePrice",
    "wholesalePrice",
    "salePrice",
    "upsetPrice",
    "retailPrice",
  ];
  if (defaultPriceArr.includes(child.dictValue)) {
    return row[child.dictValue];
  } else {
    let item = (row.goodsRedisList || []).find(item => item.priceName == child.dictValue);
    return item ? item.price : '';
  }
}
defineExpose({
  add,
  edit
});
</script>

<style lang="scss" scoped>
.tags {
  width: 80%;
  margin: 0 auto;
}

.tags,
.tag {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.tag-num {
  margin-right: 10px;
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background-color: #ff9d93;
  text-align: center;
  color: #fff;
  line-height: 40px;
  font-size: 20px;
}

.tag-name {
  height: 40px;
  line-height: 40px;
  font-size: 20px;
}

.avatar-uploader,
.el-upload {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px !important;
  height: 178px;
  display: block;
  margin-right: 10px;
}

.avatar-uploader:hover,
.el-upload:hover {
  border-color: #409eff;
}

.imgs {
  display: inline-block;
}

.avatar-uploader__img {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px !important;
  height: 178px;
  display: inline-block;
  margin-right: 10px;

  img {
    width: 178px !important;
    height: 178px;
    object-fit: fill;
  }
}

.btn {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  width: 178px !important;
  height: 178px;
  border-radius: 0 6px 0 6px;
  text-align: center;
  line-height: 178px;
}

.avatar-uploader:hover {

  // 鼠标悬浮显示按钮
  .btn {
    display: block;
  }

}

.upload-text {
  font-size: 14px;
  color: #8c939d;
  line-height: 178px;
  text-align: center;
  margin: 0 auto;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.active .tag-num {
  background-color: #ff4d3c;
}
</style>
<style type="text/css" lang="scss">
.goods_add .el-form-item .el-form-item__content {
  width: 400px !important;

  .el-input,
  .el-select {
    width: 400px !important;

  }
}

.goods_add .el-upload {
  display: block !important;
}

.goods_imgs.el-form-item .el-form-item__content {
  width: 100% !important;
}

.unit-list.el-form-item {
  margin-bottom: 0 !important;
}

.unit-list.el-form-item .el-form-item__content {
  margin-left: 0 !important;
  width: auto !important;
}
</style>